package com.eve.chatsocket.utils;

import lombok.SneakyThrows;
import okhttp3.WebSocket;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WebSocketManager {
    public static Map<String, WebSocket> SOCKET_POOL = new ConcurrentHashMap<>();
    public static Map<WebSocket,String> SESSIONID_POOL = new ConcurrentHashMap<>();
    public static void add(String key, WebSocket webSocket) {
        SOCKET_POOL.put(key, webSocket);
        SESSIONID_POOL.put(webSocket,key);
    }

    @SneakyThrows
    public static void removeAndClose(String key) {
        WebSocket webSocket = SOCKET_POOL.remove(key);
        SESSIONID_POOL.remove(webSocket);
        if (webSocket != null) {
            //session.close();
            webSocket.close(1000,"客户端主动断开链接");
        }
    }

    public static WebSocket getSocket(String key) {
        return SOCKET_POOL.get(key);
    }

    public static String getUserSessionId(WebSocket webSocket){
        return SESSIONID_POOL.get(webSocket);
    }
    public static Map<String, WebSocket> getAll(){
        return SOCKET_POOL;
    }
}
